#include <cstddef>
#include <iostream>
#include <pthread.h>
using namespace std;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int k = 1; // 1表示的是打印A
int num = 10; // 打10次
void* ThreadA(void* arg) {
    for(int i = 0; i < num; i++) {
        pthread_mutex_lock(&lock);
        while (k != 1) {
            pthread_cond_wait(&cond, &lock);
        }
        k = 0;
        cout << "我是线程A" << endl;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&lock);
    }
    return nullptr;
}

void* ThreadB(void* arg) {
    for(int i = 0; i < num; i++) {
        pthread_mutex_lock(&lock);
        while (k != 0) {
            pthread_cond_wait(&cond, &lock);
        }
        k = 1;
        cout << "我是线程B" << endl;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&lock);
    }
    return nullptr;
}

int main() {
    pthread_t tida, tidb;
    pthread_create(&tida, NULL, ThreadA, NULL);
    pthread_create(&tidb, NULL, ThreadB, NULL);
    pthread_join(tida, nullptr);
    pthread_join(tidb, nullptr);
    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&lock);
    return 0;
}